package com.itcast.demo_one.fragment

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.itcast.demo_one.R


class ListFragment : Fragment() {

    // ---------------定义接口---------
    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }
    // ---------------定义接口---------

    // 声明一个变量来保存实现了OnItemClickListener接口的监听器实例
    private var listener: OnItemClickListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_list, container, false)
    }

    // 在Fragment的视图创建完成后调用，用于初始化视图组件
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        view.findViewById<Button>(R.id.item1).setOnClickListener {
            listener?.onItemClick(0)
        }

        view.findViewById<Button>(R.id.item2).setOnClickListener {
            listener?.onItemClick(1)
        }
    }

    // 2. --------------------------------------
    // 当Fragment与Activity关联时调用
    override fun onAttach(context: Context) {
        super.onAttach(context)
        // 检查Activity是否实现了OnItemClickListener接口
        if (context is OnItemClickListener) {
            // 如果实现了，则将listener设置为该Activity的实例
            listener = context
        } else {
            // 如果没有实现，则抛出运行时异常提示必须实现OnItemSelectedListener接口
            throw RuntimeException("$context 必须实现 OnItemSelectedListener")
        }
    }

    // 当Fragment与Activity解除关联时调用
    override fun onDetach() {
        super.onDetach()
        // 将listener置为null，避免内存泄漏
        listener = null
    }

}